import styles from './index.less';
import {
  history,
  Link,
  useIntl,
  useDispatch,
  useSelector,
  useModel,
  useLocation,
} from 'umi';
import { useEffect, useState, useRef } from 'react';

import {
  Form,
  Input,
  Button,
  Tabs,
  Select,
  Popover,
  Spin,
  Upload,
  message,
  Tooltip,
  Dropdown,
  Tag,
  Menu,
} from 'antd';
import {
  CloseCircleOutlined,
  CheckCircleOutlined,
  CloseOutlined,
  LoadingOutlined,
} from '@ant-design/icons';
import moment from 'moment';
import Highlighter from 'react-highlight-words';
import request from '@/utils/request';
import config from '@/config/index';
import { getToken } from '@/utils/auth';
import {
  connectSocket,
  handleAvatarError,
  handleGroupAvatarError,
  handleAvatarErrorByType,
  getBase64,
  guid2,
  copyFn,
} from '@/utils';
import {
  DownOutlined,
  SearchOutlined,
  DashboardOutlined,
  CheckOutlined,
  FolderOpenOutlined,
} from '@ant-design/icons';
const { TabPane } = Tabs;
const { TextArea } = Input;
const { Option } = Select;

import EditContact from '@/pages/components/editContact';
import Labels from '@/pages/components/labels';

import QuickReply from './components/quickreply';

import Recorder from 'js-audio-recorder';
let recorder: any = null;
import imgWhatsapp from '@/images/whatsapp.svg';

import imgAudioIcon from '@/images/audio.png';
import imgVideoIcon from '@/images/video.png';
import imgPhotoIcon from '@/images/photo.png';
import imgDocumentIcon from '@/images/doc.png';
import imgFileIcon from '@/images/file.png';

import imgEmoji from '@/images/reply/emoji.svg';
import imgAttach from '@/images/reply/attach.svg';
import imgQuickReply from '@/images/reply/quick-reply.svg';
import imgAudioNote from '@/images/reply/audio-note.svg';

import imgNoTeam from '@/images/noteam.svg';
import imgCommonTeam from '@/images/commonteam.svg';
import imgLabelFilter from '@/images/label-filter.svg';

import imgOpenstatus from '@/images/open-status.svg';
import imgSnoozestatus from '@/images/snooze-status.svg';
import imgClosestatus from '@/images/close-status.svg';

import Emoji from '@/pages/components/emoji';

import { leadStagefn, leadSourcefn, priorityfn } from '@/data/options';

// let socket: any;
let taskRemindInterval: number = 0;
let voiceTimeout: number = 0;
let searchtimer: any;
let searchFCO: any; // Search Filter Contact Owner

let uqueryChatId = '';
const InboxPage = () => {
  const intl = useIntl();
  const chatWindow = useRef();
  const dispatch = useDispatch();

  const ulocation = useLocation();

  let socket = useSelector((state) => state.socket.socket);

  const stoageUserinfo = localStorage.getItem('userinfo') || '{}';

  const user = JSON.parse(stoageUserinfo);

  // const { userinfo: user, authenticated } = useModel('hook');

  const leadStage = leadStagefn();
  const leadSource = leadSourcefn();
  const priority = priorityfn();

  const [teamUserList, setTeamUserList] = useState([]);
  const [teamUserList1, setTeamUserList1] = useState([]);
  const [teamUserList2, setTeamUserList2] = useState([]);

  const [msgtab, setMsgtab] = useState('1');
  uqueryChatId = ulocation.query.chatId;
  const [chatUserId, setChatUserId] = useState(ulocation.query.chatId || '');

  const [chatUserList, setChatUserList] = useState([
    {
      id: '',
      image: '',
      chat: {},
      metadata: {},
      contact: {},
      name: String,
    },
  ]);

  const [selectChatUser, setSelectChatUser] = useState({
    id: '',
    image: '',
    chat: {},
    contact: {},
    metadata: {},
    name: '',
  });

  const [chatUserDetail, setChatUserDetail] = useState({
    contact: {},
    messages: [],
  });

  const [updateCUD, setUpdateCUD] = useState(0);

  // 聊天搜寻的object
  const [searchData, setSearchData] = useState({
    chats: [],
    messages: [],
    visible: false,
    keyword: '',
    chatWindowLiberate: true,
  });

  const [filterContactOwnerVisible1, setFilterContactOwnerVisible1] = useState(
    false,
  );
  const [filterContactOwnerVisible2, setFilterContactOwnerVisible2] = useState(
    false,
  );

  const [listLoading, setListLoading] = useState(true);
  const [chatInfoLoading, setChatInfoLoading] = useState(true);

  const [chatMessage, setChatMessage] = useState('');
  const [sendDisabled, setSendDisabled] = useState(true);
  const [sendLoading, setSendLoading] = useState(false);

  const [emojiVisible, setEmojiVisible] = useState(false);
  const [quickreplyVisible, setQuickReplyVisible] = useState(false);
  const [voiceStatus, setVoiceStatus] = useState(false);
  const [voiceDuration, setVoiceDuration] = useState(0);

  const [receiveMessage, setReceiveMessage] = useState({});

  const [editUserVisible, setEditUserVisible] = useState(false);

  const [toBeSentImgs, setToBeSentImgs] = useState([]);

  const [msgState, setMsgState] = useState('O');

  const [replyMsg, setReplyMsg] = useState({});
  // quotedMsgId

  useEffect(() => {
    const loadpage = sessionStorage.getItem('inboxloadpage');
    if (loadpage !== 'yes') {
      sessionStorage.setItem('inboxloadpage', 'yes');
      setTimeout(() => {
        location.reload();
      }, 100);
    } else {
      sessionStorage.removeItem('inboxloadpage');
    }

    getChatUserList();
    onConnectSocket();
    getTags();
  }, []);

  useEffect(() => {
    if (chatUserId && chatUserId !== 'undefined') {
      getChatDetailByUser(chatUserId);
    }
  }, [chatUserId]);

  useEffect(() => {
    setChatUserId(ulocation.query.chatId);
    uqueryChatId = ulocation.query.chatId;
  }, [ulocation.query.chatId]);

  useEffect(() => {
    if (chatMessage && chatMessage.length > 0) {
      setSendDisabled(false);
    }
    if (toBeSentImgs && toBeSentImgs.length > 0) {
      setSendDisabled(false);
    }
    if (!chatMessage && !toBeSentImgs.length) {
      setSendDisabled(true);
    }
  }, [chatMessage, toBeSentImgs]);

  const onConnectSocket = () => {
    if (!socket) {
      socket = connectSocket(user.id, {
        success: () => {},
        fail: () => {},
        receive: handleMessage,
      });
      dispatch({ type: 'socket/setSocket', socket });
    } else {
      socket.onmessage = handleMessage;
    }
  };

  // 接收socket返回的消息
  useEffect(() => {
    if (!receiveMessage || !receiveMessage.id) {
      return;
    }
    const data: any = receiveMessage;
    console.log('socket 收到的消息: ', data);
    console.log('当前选择聊天的人:', selectChatUser);

    const receiveMsg = {
      ...data,
      author: data.sendUserId,
      // caption: data.caption,
      chatId: user.chatapiId,
      // chatName: data.chatName,
      quotedMsgId: data.quotedMsgId,
      quotedMsgBody: data.quotedMsgBody,
      fromMe: true,
      id: data.messagesId,
      isForwarded: 0,
      messageNumber: data.content ? data.content.length : 0,
      self: data.sendUserId === user.chatapiId ? 1 : 0,
      time: data.createdDate / 1000,
      senderName: data.senderName,
      // type: data.type,
      loading: false,
    };
    const ddi = dialogsData.dialogs.findIndex(
      (n) =>
        n.contact.chatId == data.sendUserId ||
        n.contact.chatId == data.receiveUserId,
    );
    if (ddi >= 0) {
      const ddates = dialogsData.dialogs;
      ddates[ddi].chat = Object.assign({}, ddates[ddi].chat, data);
      setDialogsData({
        ...dialogsData,
        dialogs: ddates,
      });
    }
    if (
      chatUserDetail.contact.chatId &&
      (chatUserDetail.contact.chatId == data.sendUserId ||
        chatUserDetail.contact.chatId == data.receiveUserId)
    ) {
      const lists = { ...chatUserDetail };
      if (lists.messages) {
        // 判断这条消息id是否已经在chatWindow里了
        const hasMsg = lists.messages.findIndex(
          (n) => n.id === data.messagesId,
        );
        if (hasMsg >= 0) {
          lists.messages[hasMsg] = receiveMsg;
        } else {
          lists.messages.push(receiveMsg);
        }
      } else {
        lists.messages = [receiveMsg];
      }
      setChatUserDetail(lists);
      setUpdateCUD(updateCUD + 1);
    }
    const cus = [...chatUserList];
    const sendIndex = cus.findIndex((n) => n.id === data.sendUserId);
    if (sendIndex >= 0) {
      cus[sendIndex].messages = receiveMsg;
      setChatUserList(cus);
    }
    const receiveIndex = cus.findIndex((n) => n.id === data.receiveUserId);
    if (receiveIndex >= 0) {
      cus[receiveIndex].messages = receiveMsg;
      setChatUserList(cus);
    }
  }, [receiveMessage]);

  const handleMessage = (msg: any) => {
    console.log('msg', msg);
    try {
      const data = JSON.parse(msg.data);
      setReceiveMessage(data);
    } catch (error) {
      console.log('handleMessage try catch err', error);
    }
  };

  const defaultFilterUser = {
    id: user.id,
    name: 'u',
  };
  const [filterUser, setFilterUser] = useState(defaultFilterUser);
  const [dialogsData, setDialogsData] = useState({
    dialogs: [],
    unAssignedDialogs: [],
  });

  const getChatUserList = (flag: any) => {
    setListLoading(!flag);
    request
      .get(`/chat/dialogs`)
      .then((res) => {
        setDialogsData(res.data);
        setTeamUserList(res.data.userList || []);
        setTeamUserList1(res.data.userList || []);
        setTeamUserList2(res.data.userList || []);

        getFilterMessage(res.data, flag);
        setListLoading(false);
      })
      .catch((err) => {
        setListLoading(false);
      });
  };

  useEffect(() => {
    getFilterMessage('', '');
    // console.log('第一次执行')
  }, [filterUser, msgState]);

  const getFilterMessage = (data: any, flag: any) => {
    const { dialogs = [], unAssignedDialogs = [] } = data || dialogsData;
    let list = dialogs;
    if (filterUser && filterUser.id) {
      list = dialogs.filter((n: any) => n.contact.assignedId === filterUser.id);
    } else if (filterUser.name === intl.formatMessage({ id: 'unassigned' })) {
      // 未委派
      list = unAssignedDialogs.map((n) => {
        return {
          ...n,
          chat: n.chat || {},
        };
      });
    }

    const filterStateList = list.filter(
      (n: any) => n.contact.state === msgState,
    );
    setChatUserList(filterStateList);

    if (!uqueryChatId && filterStateList.length > 0) {
      // onViewChatByUser(filterStateList[0], '', flag);
      setSelectChatUser(filterStateList[0]);
      history.push(`/inbox?chatId=${filterStateList[0].contact.chatId}`);
    }
  };

  // 初始化 设置 selectChatUser
  useEffect(() => {
    let lcid = chatUserDetail.contact.lastChatId;
    if (lcid) {
      const su = chatUserList.find((n) => n.chat.id === lcid);
      if (su) {
        setSelectChatUser(su);
      }
    }
  }, [chatUserList, chatUserDetail.contact.lastChatId]);

  const getStateMsgLength = (state: string) => {
    const { dialogs = [], unAssignedDialogs = [] } = dialogsData;
    const dl = dialogs.filter((n: any) => n.contact.state === state);
    const ul = unAssignedDialogs.filter((n: any) => n.contact.state === state);
    return dl.length + ul.length;
  };

  const getChatDetailByUser = (chatId: string) => {
    setChatInfoLoading(true);
    setChatMessage('');
    setToBeSentImgs([]);
    request.get(`/chat/${chatId}`).then((res) => {
      setChatInfoLoading(false);
      setChatUserDetail(res.data);
      setUpdateCUD(updateCUD + 1);

      // setSChatUser(res.data.contact.lastChatId)
    });
  };
  useEffect(() => {
    onChatWindowLandScrollBar(false);
  }, [updateCUD]);

  const onChatWindowLandScrollBar = (next: any) => {
    // 把聊天窗口的滚动条滚动到最底
    if (chatWindow && chatWindow.current) {
      if (searchData.chatWindowLiberate) {
        chatWindow.current.scrollTop = chatWindow.current.scrollHeight * 999;
      } else {
        const itemIndex = chatUserDetail.messages.findIndex(
          (n) => n.id === selectChatUser.chat.id,
        );
        if (chatWindow.current.children[itemIndex]) {
          chatWindow.current.scrollTop =
            chatWindow.current.children[itemIndex].offsetTop - 400;
        }
      }
      if (!next) {
        setTimeout(() => {
          onChatWindowLandScrollBar(true);
        }, 1000);
      }
    }
  };

  useEffect(() => {
    if (searchData.keyword) {
      searchChat();
    } else {
      setSearchData({
        ...searchData,
        visible: false,
        chats: [],
        messages: [],
      });
    }
  }, [searchData.keyword]);

  const searchChat = () => {
    setListLoading(true);
    request
      .post(`/chat/search`, { keyword: searchData.keyword })
      .then((res) => {
        const { chats = [], messages = [] } = res.data;
        setListLoading(false);
        setSearchData({
          ...searchData,
          visible: true,
          chats,
          messages,
        });
      })
      .catch(() => {
        setListLoading(false);
      });
  };

  const handleSearch = (e: any) => {
    setSearchData({
      ...searchData,
      keyword: e.target.value,
    });
    searchChat();
  };
  const handleSearchKeyword = (e: any) => {
    clearTimeout(searchtimer);
    searchtimer = setTimeout(() => {
      setSearchData({
        ...searchData,
        keyword: e.target.value,
      });
    }, 500);
  };

  const onViewChatByUser = (item: any, message: any, flag: any) => {
    history.replace(`/inbox?chatId=${item.contact.chatId}`);
    setSelectChatUser(item);

    if (!flag) {
      getChatDetailByUser(item.contact.chatId);
    }

    setSearchData({
      ...searchData,
      chatWindowLiberate: !message,
    });
  };

  const onChangeTab = (key: string) => {
    setMsgtab(key);
  };

  const onChangeChatMessage = (e: any) => {
    const { value } = e.target;
    setChatMessage(value);
  };

  const enterSendBtn = (event: any) => {
    if (sendLoading || sendDisabled) {
      event.preventDefault();
      return;
    }
    if (event.key == 'Enter' || event.code == 'Enter' || event.keyCode == 13) {
      if (!event.ctrlKey) {
        event.preventDefault();
        onSendMessage();
      } else {
        setChatMessage(chatMessage + '\n');
      }
    }
  };

  // 发送消息
  const onSendMessage = () => {
    console.log('toBeSentImgs', toBeSentImgs);
    if (toBeSentImgs.length) {
      // n : { fileName, url }
      toBeSentImgs.forEach((n: any, i: number) => {
        const isLast = i === toBeSentImgs.length - 1;
        const data = {
          receiveUserId: chatUserDetail.contact.chatId,
          ...n,
        };
        if (replyMsg.messagesId) {
          data.quotedMsgId = replyMsg.messagesId;
          data.quotedMsgBody = replyMsg.content;
        }
        if (isLast) {
          data.caption = chatMessage;
          setChatMessage('');
          setToBeSentImgs([]);
        }

        // 发送内部讯息
        if (msgtab === '2') {
          sendNote({
            ...data,
            content: data.url,
            type: 'image',
          });
          return;
        }

        setSendLoading(true);

        const uuid = guid2();

        onSendLoadingMessage({
          content: n.url,
          caption: data.caption || data.fileName,
          quotedMsgId: data.quotedMsgId,
          quotedMsgBody: data.quotedMsgBody,
          type: 'image',
          loading: true,
          uuid,
        });
        setReplyMsg({});
        request
          .post('/chat/sendFileUrl', data)
          .then((res) => {
            onSendLoadingMessage({
              content: n.url,
              caption: data.caption || data.fileName,
              quotedMsgId: data.messagesId,
              quotedMsgBody: data.content,
              type: 'image',
              id: res.data.id,
              loading: false,
              uuid,
            });

            updateLeftListMsg(res.data);

            message.success(intl.formatMessage({ id: 'sendsuccess' }));
            if (isLast) {
              setSendLoading(false);
            }
            setReplyMsg({});
          })
          .catch((err) => {
            message.error(err.message);
            if (isLast) {
              setSendLoading(false);
            }
          });
      });
      return;
    }
    const data = {
      receiveUserId: chatUserDetail.contact.chatId,
      content: chatMessage,
    };
    if (replyMsg.messagesId) {
      data.quotedMsgId = replyMsg.messagesId;
      data.quotedMsgBody = replyMsg.content;
    }
    // 发送内部讯息
    if (msgtab === '2') {
      sendNote({
        ...data,
        type: 'chat',
      });
      return;
    }

    setSendLoading(true);
    setChatMessage('');
    const uuid = guid2();
    onSendLoadingMessage({
      content: data.content,
      quotedMsgId: data.quotedMsgId,
      quotedMsgBody: data.quotedMsgBody,
      type: 'chat',
      loading: true,
      uuid,
    });
    setReplyMsg({});
    request
      .post('/chat/sendMessage', data)
      .then((res) => {
        onSendLoadingMessage({
          content: data.content,
          quotedMsgId: data.messagesId,
          quotedMsgBody: data.content,
          type: 'chat',
          id: res.data.id,
          loading: false,
          uuid,
        });
        updateLeftListMsg(res.data);

        message.success(intl.formatMessage({ id: 'sendsuccess' }));
        setSendLoading(false);
      })
      .catch((err) => {
        message.error(err.message);
        setChatMessage('');
        setSendLoading(false);
        setReplyMsg({});
      });
  };

  const updateLeftListMsg = (chat: any) => {
    const index = chatUserList.findIndex(
      (n) => n.id === chatUserDetail.contact.chatId,
    );
    if (index >= 0) {
      chatUserList[index].chat = chat;
    }
  };

  const onSendLoadingMessage = (data: any) => {
    const receiveMsg = {
      ...data,
      author: user.chatapiId,
      // body: data.content,
      // type: data.type,
      chatId: user.chatapiId,
      chatName: user.name,
      fromMe: true,
      id: data.id,
      messageNumber: data.content ? data.content.length : 0,
      self: 1,
      time: new Date().getTime() / 1000,
      senderName: chatUserDetail.contact.name,
      loading: !!data.loading,
    };

    console.log('onSendLoadingMessage', receiveMsg, data);

    if (chatUserDetail.contact.id) {
      const lists = { ...chatUserDetail };
      if (lists.messages) {
        const hasMsgIndex = lists.messages.findIndex(
          (n: any) => n.uuid === data.uuid || n.id === data.id,
        );
        hasMsgIndex >= 0
          ? (lists.messages[hasMsgIndex] = receiveMsg)
          : lists.messages.push(receiveMsg);
      } else {
        lists.messages = [receiveMsg];
      }
      setChatUserDetail(lists);
      setUpdateCUD(updateCUD + 1);
    }
  };

  const onSelectEmoji = (emoji: string) => {
    //选择表情的回调函数
    setChatMessage(chatMessage + emoji);
    setEmojiVisible(false);
  };

  const uploadProps = {
    name: 'file',
    action: (file: { type: string }) => {
      if (file.type.indexOf('image/') >= 0) {
        // 如果上传的文件是图片的话
        return config.baseURL + '/system/fileUpload';
      }
      return config.baseURL + '/chat/sendFile';
    },
    showUploadList: false,
    data: { receiveUserId: chatUserDetail.contact.chatId },
    headers: {
      'Access-Token': getToken(),
    },
    onChange(info: any) {
      console.log(info);
      const { file, fileList } = info;
      if (info.file.status !== 'uploading') {
      }
      if (info.file.status === 'done') {
        const { type, response } = file;
        if (type.indexOf('image/') >= 0) {
          const imgs = [...toBeSentImgs];
          imgs.push(response.data);
          setToBeSentImgs(imgs);
        } else {
          onSendLoadingMessage({
            ...response.data,
            loading: false,
          });

          updateLeftListMsg(response.data);

          message.success(intl.formatMessage({ id: 'sendsuccess' }));
        }
      } else if (info.file.status === 'error') {
        message.success('send failed');
      }
    },
  };

  const onRemoveToBeSentImg = (i: number) => {
    const imgs = [...toBeSentImgs];
    imgs.splice(i, 1);
    setToBeSentImgs(imgs);
  };

  // 选择快捷回复的回调
  const onSelectedQuickReply = (item: any) => {
    setChatMessage(item.content);
    setToBeSentImgs(item.attachmentList || []);
    setQuickReplyVisible(false);
  };

  const onClickVoice = () => {
    if (!recorder) {
      recorder = new Recorder();
    }
    recorder.start().then(
      () => {
        // 开始录音
        setVoiceStatus(true);
        voiceTimeout = setInterval(() => {
          setVoiceDuration((voiceDuration) => voiceDuration + 1);
        }, 1000);
      },
      (error) => {
        // 出错了
        console.log(error);
        setVoiceStatus(false);
      },
    );
  };

  const onCloseVoiceing = () => {
    stopVoice();
  };
  const onCheckVoiceing = () => {
    const voiceBlog = recorder.getWAVBlob();
    const formData = new FormData();
    formData.append('file', voiceBlog);
    formData.append('receiveUserId', chatUserDetail.contact.chatId);
    const uuid = guid2();
    onSendLoadingMessage({
      content: 'video.bin',
      type: 'ptt',
      loading: true,
      uuid,
    });
    request.post('/chat/sendPTT', formData).then((res) => {
      onSendLoadingMessage({
        content: res.data.content,
        id: res.data.id,
        type: 'ptt',
        loading: false,
        uuid,
      });
      updateLeftListMsg(res.data);
      message.success(intl.formatMessage({ id: 'sendsuccess' }));
    });
    stopVoice();
  };

  const stopVoice = () => {
    recorder.destroy();
    recorder = null;
    setVoiceStatus(false);
    clearInterval(voiceTimeout);
    setVoiceDuration(0);
  };

  interface NoteData {
    content: string;
    caption: string;
    type: string;
    receiveUserId: string;
  }
  const sendNote = (data: NoteData) => {
    console.log('data', data);
    setSendLoading(true);
    setChatMessage('');
    const uuid = guid2();
    onSendLoadingMessage({
      caption: data.caption,
      content: data.content,
      type: data.type,
      loading: true,
      isNote: 'Y',
      uuid,
    });
    request.post('/chat/sendNote', data).then((res) => {
      onSendLoadingMessage(
        Object.assign({
          caption: data.caption,
          content: data.content,
          type: data.type,
          id: res.data.id,
          loading: false,
          isNote: 'Y',
          uuid,
        }),
      );
      message.success(intl.formatMessage({ id: 'sendsuccess' }));
      setSendLoading(false);
    });
  };

  const renderChatListDes = (item: any) => {
    if (item) {
      let content: any = '';
      switch (item.type) {
        case 'chat':
          content = item.content;
          break;
        case 'image':
          content = (
            <div>
              <img src={imgPhotoIcon} alt="" style={{ marginRight: 4 }} />
              image
            </div>
          );
          break;
        case 'video':
          content = (
            <div>
              <img src={imgVideoIcon} alt="" style={{ marginRight: 4 }} />
              video
            </div>
          );
          break;
        case 'ptt':
        case 'audio':
          content = (
            <div>
              <img src={imgAudioIcon} alt="" style={{ marginRight: 4 }} />
              {/* ptt */}
            </div>
          );
          break;
        case 'document':
          content = (
            <div>
              <img src={imgDocumentIcon} alt="" style={{ marginRight: 4 }} />
              {item.caption}
            </div>
          );
          break;
        default:
          break;
      }
      return content;
    }
    return '';
  };

  // 更新联系人信息成功的回调函数
  const onUpdateContactSuccess = (contact: any) => {
    if (
      chatUserDetail.contact.assignedId != contact.assignedId ||
      chatUserDetail.contact.name != contact.name
    ) {
      history.push(`/inbox?chatId=${contact.chatId}&n=${new Date().getTime()}`);
      getChatUserList();
    }
    setChatUserDetail({
      ...chatUserDetail,
      contact,
    });
    setUpdateCUD(updateCUD + 1);
  };

  const onChangeState = (state: string) => {
    request
      .patch('/contact/edit', { id: chatUserDetail.contact.id, state })
      .then((res) => {
        if (msgState !== state) {
          const cus = { ...dialogsData };
          const i = cus.dialogs.findIndex(
            (n) => n.contact.id === chatUserDetail.contact.id,
          );
          cus.dialogs[i].contact.state = state;
          getFilterMessage(cus);
          setSelectChatUser({
            id: '',
            image: '',
            chat: {},
            contact: {},
            metadata: {},
            name: '',
          });
        }
      });
  };

  const onSelectedContactOwner = (item) => {
    request
      .patch('contact/edit', {
        id: chatUserDetail.contact.id,
        assignedId: item.id,
      })
      .then((res) => {
        setChatUserDetail({
          ...chatUserDetail,
          contact: res.data.contact,
        });
      });
    setFilterContactOwnerVisible2(false);
  };

  const changeSFCOVisible1 = (visible: boolean) => {
    setFilterContactOwnerVisible1(visible);
  };
  const changeSFCOVisible2 = (visible: boolean) => {
    setFilterContactOwnerVisible2(visible);
  };

  const onSearchInputFilterContactOwner1 = (e: any) => {
    clearTimeout(searchFCO);
    searchFCO = setTimeout(() => {
      const { value } = e.target;
      const list = [];
      teamUserList.forEach((item) => {
        const nv = item.name ? item.name.indexOf(value) >= 0 : 0;
        const lv = item.lastName ? item.lastName.indexOf(value) >= 0 : 0;
        if (!value || nv || lv) {
          list.push({ ...item, hide: false });
        } else {
          list.push({ ...item, hide: true });
        }
      });
      setTeamUserList1(list);
    }, 200);
  };

  const onSearchInputFilterContactOwner2 = (e: any) => {
    clearTimeout(searchFCO);
    searchFCO = setTimeout(() => {
      const { value } = e.target;
      const list = [];
      teamUserList.forEach((item) => {
        const nv = item.name ? item.name.indexOf(value) >= 0 : 0;
        const lv = item.lastName ? item.lastName.indexOf(value) >= 0 : 0;
        if (!value || nv || lv) {
          list.push({ ...item, hide: false });
        } else {
          list.push({ ...item, hide: true });
        }
      });
      setTeamUserList2(list);
    }, 200);
  };

  const renderSelectContactOwner = () => {
    return (
      <div className={styles.dropdownBox}>
        <Input
          className={styles.searchInput}
          size="large"
          placeholder={intl.formatMessage({ id: 'search' })}
          prefix={<SearchOutlined />}
          onInput={onSearchInputFilterContactOwner2}
        />
        <div className={styles.dbItems}>
          {teamUserList2.map((n, i) =>
            n.id !== chatUserDetail.contact.id && !n.hide ? (
              <div
                key={i}
                className={styles.dbItem}
                onClick={(e) => onSelectedContactOwner(n)}
              >
                <img
                  className={styles.itemAvatar}
                  src={n.avatar || ''}
                  onError={handleAvatarError}
                />
                <span className={styles.itemName}>{n.name}</span>
                <span className={styles.itemName}>{n.lastName}</span>
              </div>
            ) : null,
          )}
        </div>
      </div>
    );
  };

  const onFilterContactOwner = (item: any) => {
    if (item === 'u') {
      setFilterUser(defaultFilterUser);
      // getChatUserList()
    } else if (item === 'un') {
      setFilterUser({
        id: null,
        name: intl.formatMessage({ id: 'unassigned' }),
      });
    } else if (item === 'all') {
      setFilterUser({
        id: null,
        name: intl.formatMessage({ id: 'allAssigned' }),
      });
      // getChatUserList()
    } else {
      setFilterUser(item);
    }
    setFilterContactOwnerVisible1(false);
  };

  const renderFilterContactOwner = () => {
    return (
      <div className={styles.dropdownBox}>
        <div className={styles.dbItems}>
          <div
            className={styles.dbItem}
            onClick={() => onFilterContactOwner('u')}
          >
            <img
              className={styles.itemAvatar}
              src={user.avatar}
              onError={handleAvatarError}
            />
            <span className={styles.itemName}>
              {intl.formatMessage({ id: 'u' })}
            </span>
            <span className={styles.itemNum}>
              {teamUserList.find((n) => n.id === user.id)
                ? teamUserList.find((n) => n.id === user.id).assignedCount
                : 0}
            </span>
          </div>
          <div
            className={styles.dbItem}
            onClick={() => onFilterContactOwner('un')}
          >
            <img className={styles.itemAvatar} src={imgNoTeam} />
            <span className={styles.itemName}>
              {intl.formatMessage({ id: 'unassigned' })}
            </span>
            <span className={styles.itemNum}>
              {dialogsData.unAssignedDialogs.length}
            </span>
          </div>
          <div
            className={styles.dbItem}
            onClick={() => onFilterContactOwner('all')}
          >
            <img className={styles.itemAvatar} src={imgCommonTeam} />
            <span className={styles.itemName}>
              {intl.formatMessage({ id: 'allAssigned' })}
            </span>
            <span className={styles.itemNum}>{dialogsData.dialogs.length}</span>
          </div>
        </div>
        {user.type === 'captain' ? (
          <div>
            <Input
              className={styles.searchInput}
              placeholder={intl.formatMessage({ id: 'search' })}
              prefix={<SearchOutlined />}
              onInput={onSearchInputFilterContactOwner1}
            />
            <div className={styles.dbItems}>
              {teamUserList1.map((n, i) =>
                !n.hide ? (
                  <div
                    key={i}
                    className={styles.dbItem}
                    onClick={() => onFilterContactOwner(n)}
                  >
                    <img
                      className={styles.itemAvatar}
                      src={n.avatar || ''}
                      onError={handleAvatarError}
                    />
                    <span className={styles.itemName}>{n.name}</span>
                    <span className={styles.itemName}>{n.lastName}</span>
                    <span className={styles.itemNum}>{n.assignedCount}</span>
                  </div>
                ) : null,
              )}
            </div>
          </div>
        ) : null}
      </div>
    );
  };

  const msgStateInfo = (type: string) => {
    const data = {
      icon: imgOpenstatus,
      name: intl.formatMessage({ id: 'open' }),
    };
    switch (msgState) {
      case 'O':
        data.icon = imgOpenstatus;
        data.name = intl.formatMessage({ id: 'open' });
        break;
      case 'S':
        data.icon = imgSnoozestatus;
        data.name = intl.formatMessage({ id: 'snooze' });
        break;
      case 'C':
        data.icon = imgClosestatus;
        data.name = intl.formatMessage({ id: 'closed' });
        break;
    }
    return data[type];
  };

  const renderStatusFilter = () => {
    return (
      <div className={styles.dropdownBox} style={{ width: 140, padding: 20 }}>
        <div className={styles.dbItems}>
          <div className={styles.dbItem} onClick={() => onChangeMsgState('O')}>
            <img className={styles.itemAvatar} src={imgOpenstatus} />
            <span className={styles.itemName}>
              {intl.formatMessage({ id: 'open' })}
            </span>
            <span className={styles.itemNum}>{getStateMsgLength('O')}</span>
          </div>
          {/* <div className={styles.dbItem} onClick={() => onChangeMsgState('S')}>
            <img className={styles.itemAvatar} src={imgSnoozestatus} />
            <span className={styles.itemName}>
              {intl.formatMessage({ id: 'snooze' })}
            </span>
            <span className={styles.itemNum}>{getStateMsgLength('S')}</span>
          </div> */}
          <div className={styles.dbItem} onClick={() => onChangeMsgState('C')}>
            <img className={styles.itemAvatar} src={imgClosestatus} />
            <span className={styles.itemName}>
              {intl.formatMessage({ id: 'closed' })}
            </span>
            <span className={styles.itemNum}>{getStateMsgLength('C')}</span>
          </div>
        </div>
      </div>
    );
  };

  const [tagNames, setTagNames] = useState([
    {
      tagName: String,
      count: Number,
    },
  ]);
  const [selectedTags, setSelectedTags] = useState([]);

  const getTags = () => {
    request
      .get('/tag/tagNames')
      .then((res) => {
        setTagNames(res.data.tagNames || []);
      })
      .catch(() => {
        setTagNames([]);
      });
  };

  const onClickTag = (n: any) => {
    const sarr = [...selectedTags];
    sarr.push(n);
    setSelectedTags(sarr);
  };

  const onCloseSelectedTag = (n) => {
    const sarr = [...selectedTags];
    const i = sarr.findIndex((m) => m.tagName === n.tagName);
    sarr.splice(i, 1);
    setSelectedTags(sarr);
  };

  const tagFilterReturnBool = (list) => {
    if (!selectedTags.length) {
      return true;
    }
    for (let i = 0; i < selectedTags.length; i++) {
      const n = selectedTags[i];
      const fi = list.findIndex((m) => m.tagName === n.tagName);
      console.log('fi', list, fi, i, selectedTags);
      if (fi < 0) {
        return false;
      }
    }
    return true;
  };

  const renderLabelFilter = () => {
    return (
      <div className={styles.dropdownBox} style={{ width: 100, padding: 20 }}>
        <div className={styles.dbItems}>
          {tagNames.map((n, i) => (
            <Tag
              key={i}
              color={n.color}
              style={{ marginBottom: 10, cursor: 'pointer' }}
              onClick={() => onClickTag(n)}
            >
              {n.tagName}
            </Tag>
          ))}
        </div>
      </div>
    );
  };

  const onChangeMsgState = (state: string) => {
    setMsgState(state);
  };

  const chatFuntionBlock = (item: any) => {
    return (
      <Menu>
        {!item.quoteMsgId ? (
          <Menu.Item onClick={() => onSetReplyMsg(item)}>
            {intl.formatMessage({ id: 'reply' })}
          </Menu.Item>
        ) : null}
        {item.type === 'chat' ? (
          <Menu.Item
            onClick={() => {
              copyFn(item.content);
            }}
          >
            {intl.formatMessage({ id: 'copy' })}
          </Menu.Item>
        ) : null}
      </Menu>
    );
  };

  const onSetReplyMsg = (item) => {
    console.log(item);
    setReplyMsg(item);
  };
  const onClearReplyMsg = () => {
    setReplyMsg({});
  };

  return (
    <div className={styles.inboxContainer}>
      <div className={styles.inboxLeft}>
        <div className={styles.headC}>
          {user.type === 'captain' ? (
            <Popover
              visible={filterContactOwnerVisible1}
              placement="bottomRight"
              content={renderFilterContactOwner}
              trigger={['click']}
              onVisibleChange={changeSFCOVisible1}
            >
              <div
                className={styles.headTop}
                onClick={() => setFilterContactOwnerVisible1(true)}
              >
                <span className={styles.itemtext}>
                  {intl.formatMessage({ id: filterUser.name })}
                </span>
                <DownOutlined style={{ fontSize: 12 }} />
              </div>
            </Popover>
          ) : (
            <div></div>
          )}

          <Dropdown overlay={renderLabelFilter} trigger={['click']}>
            <div className={styles.headMenu}>
              <div className={styles.menuItem}>
                <img className={styles.menuItemIcon} src={imgLabelFilter} />
                <span className={styles.itemtext}>
                  {intl.formatMessage({ id: 'labels' })}
                </span>
                <DownOutlined style={{ fontSize: 12 }} />
              </div>
            </div>
          </Dropdown>

          <Dropdown overlay={renderStatusFilter} trigger={['click']}>
            <div className={styles.headMenu}>
              <div className={styles.menuItem}>
                <img
                  className={styles.menuItemIcon}
                  src={msgStateInfo('icon')}
                />
                <span className={styles.itemtext}>{msgStateInfo('name')}</span>
                <DownOutlined style={{ fontSize: 12 }} />
              </div>
            </div>
          </Dropdown>
        </div>

        {selectedTags.length > 0 ? (
          <div className={styles.tags}>
            {selectedTags.map((n, i) => (
              <Tag key={i} color={n.color} className={styles.tag}>
                {n.tagName}
                <CloseOutlined onClick={() => onCloseSelectedTag(n)} />
              </Tag>
            ))}
          </div>
        ) : null}

        <div className={styles.search}>
          <Input
            className={styles.searchInput}
            size="large"
            placeholder={intl.formatMessage({ id: 'search' })}
            // value={keyword}
            prefix={<SearchOutlined />}
            onChange={handleSearchKeyword}
            onPressEnter={(e) => handleSearch(e)}
          />
        </div>
        <div className={styles.peoples}>
          {listLoading ? (
            <div className="spinstatus">
              <Spin />
            </div>
          ) : (
            ''
          )}
          {searchData.visible ? (
            searchData.chats.length || searchData.messages.length ? (
              <div className={styles.items}>
                <div className={styles.itemsTitle}>
                  {intl.formatMessage({ id: 'chats' })}
                </div>
                {searchData.chats.map((n: any, i: number) => (
                  <div
                    key={i}
                    className={`${styles.item} ${
                      n.id === selectChatUser.id ? styles.selected : ''
                    }`}
                    onClick={() => onViewChatByUser(n)}
                  >
                    <div className={styles.avatarCon}>
                      <img
                        src={n.image || ''}
                        className={styles.avatarimg}
                        onError={(e) =>
                          handleAvatarErrorByType(e, n.metadata.isGroup)
                        }
                        alt=""
                      />
                    </div>
                    <div className={styles.info}>
                      <div className={styles.header}>
                        <div className={styles.name}>
                          <Highlighter
                            highlightStyle={{
                              backgroundColor: '#ffc069',
                              padding: 0,
                            }}
                            searchWords={[searchData.keyword]}
                            autoEscape
                            textToHighlight={n.name ? n.name.toString() : ''}
                          />
                        </div>
                        <div className={styles.time}>
                          {moment(n.chat.sendDate).format('YYYY-MM-DD HH:mm')}
                        </div>
                      </div>
                      <div className={styles.description}>
                        {renderChatListDes(n.chat)}
                      </div>
                    </div>
                  </div>
                ))}
                <div className={styles.itemsTitle}>
                  {intl.formatMessage({ id: 'messages' })}
                </div>
                {searchData.messages.map((n: any, i: number) => (
                  <div
                    key={i}
                    className={`${styles.item} ${
                      n.chat.id === selectChatUser.chat.id
                        ? styles.selected
                        : ''
                    }`}
                    onClick={() => onViewChatByUser(n, 1)}
                  >
                    <div className={styles.avatarCon}>
                      <img
                        src={n.image || ''}
                        className={styles.avatarimg}
                        onError={(e) =>
                          handleAvatarErrorByType(e, n.metadata.isGroup)
                        }
                        alt=""
                      />
                    </div>
                    <div className={styles.info}>
                      <div className={styles.header}>
                        <div className={styles.name}>{n.name}</div>
                        <div className={styles.time}>
                          {moment(n.chat.sendDate).format('YYYY-MM-DD HH:mm')}
                        </div>
                      </div>
                      <div className={styles.description}>
                        {n.chat && n.chat.type === 'chat' ? (
                          <Highlighter
                            highlightStyle={{
                              backgroundColor: '#ffc069',
                              padding: 0,
                            }}
                            searchWords={[searchData.keyword]}
                            autoEscape
                            textToHighlight={
                              n.chat.content ? n.chat.content.toString() : ''
                            }
                          />
                        ) : (
                          renderChatListDes(n.chat)
                        )}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className={styles.itemsTitle}>no resule found</div>
            )
          ) : (
            <div className={styles.items}>
              {chatUserList.map((n: any, i: number) =>
                tagFilterReturnBool(n.contact.tagList) ? (
                  <div
                    key={i}
                    className={`${styles.item} ${
                      n.chat && n.chat.id === selectChatUser.chat.id
                        ? styles.selected
                        : ''
                    }`}
                    onClick={() => onViewChatByUser(n)}
                  >
                    <div className={styles.itemHead}>
                      <div className={styles.avatarCon}>
                        <img
                          src={n.image || ''}
                          className={styles.avatarimg}
                          onError={(e) =>
                            handleAvatarErrorByType(e, n.metadata.isGroup)
                          }
                          alt=""
                        />
                      </div>
                      <div className={styles.info}>
                        <div className={styles.header}>
                          <div className={styles.name}>{n.contact.name}</div>
                          <div className={styles.time}>
                            {n.chat
                              ? moment(n.chat.sendDate).format(
                                  'YYYY-MM-DD HH:mm',
                                )
                              : ''}
                          </div>
                        </div>
                        <div className={styles.description}>
                          {/* {n.messages && (
                        n.message.type === 'chat' ? n.messages.body : ''
                      )} */}
                          {n.chat ? renderChatListDes(n.chat) : ''}
                        </div>
                      </div>
                    </div>
                    {n.contact.tagList && n.contact.tagList.length ? (
                      <div className={styles.tags}>
                        {n.contact.tagList.map((n, i) => (
                          <Tag key={i} color={n.color} className={styles.tag}>
                            {n.tagName}
                          </Tag>
                        ))}
                      </div>
                    ) : null}
                  </div>
                ) : null,
              )}
            </div>
          )}
        </div>
      </div>
      <div
        className={`${styles.inboxRight} ${chatUserId ? styles.visible : ''}`}
      >
        {chatInfoLoading ? (
          <div className={`spinstatus ${styles.spinstatus}`}>
            <Spin />
          </div>
        ) : null}
        <div className={styles.chat}>
          <div className={styles.chatHeader}>
            <div className={styles.chLeft}>
              {/* <Link
                className={styles.name}
                to={`/profile/${selectChatUser.id}`}
              >
                {selectChatUser.name}
              </Link> */}
              <span>{chatUserDetail.contact.name}</span>
              {/* <span className={styles.onlinestatus}>在线</span> */}
              {/* <Select className={styles.selecte} tagRender={accountTagRender}>
                {accountList.map((n, i) => (
                  <Option value={n} key={i}>
                    {accountTagRender(n)}
                  </Option>
                ))}
              </Select> */}
            </div>
            <div className={styles.chRight}>
              {/* <Button
                shape="circle"
                icon={<DashboardOutlined />}
                size="small"
              /> */}
              {selectChatUser.contact.state === 'C' ? (
                <Button
                  shape="circle"
                  icon={<FolderOpenOutlined />}
                  size="small"
                  className={styles.confrimok}
                  onClick={() => onChangeState('O')}
                />
              ) : (
                <Button
                  shape="circle"
                  icon={<CheckOutlined />}
                  size="small"
                  className={styles.confrimok}
                  onClick={() => onChangeState('C')}
                />
              )}
              {user.type === 'captain' ? (
                <Popover
                  visible={filterContactOwnerVisible2}
                  placement="bottomLeft"
                  content={renderSelectContactOwner}
                  trigger="click"
                  onVisibleChange={changeSFCOVisible2}
                >
                  <div
                    className={styles.dropdowncon}
                    onClick={() => setFilterContactOwnerVisible2(true)}
                  >
                    <img
                      className={styles.img}
                      src={selectChatUser.contact.assignedAvatar || ''}
                      onError={handleAvatarError}
                      alt=""
                    />
                    <span className={styles.name}>
                      {chatUserDetail.contact.assignedName}
                    </span>
                    <DownOutlined style={{ fontSize: 12 }} />
                  </div>
                </Popover>
              ) : null}
            </div>
          </div>
          <div className={styles.chatWindow} id="chatwindow" ref={chatWindow}>
            {chatUserDetail.messages.map((n: any, i: number) => (
              <div
                key={i}
                className={`${styles.chatItem} ${n.self ? styles.self : ''} ${
                  n.isNote === 'Y' ? styles.note : ''
                }`}
              >
                <div className={styles.avatarcon}>
                  {i === 0 || n.self !== chatUserDetail.messages[i - 1].self ? (
                    <div className={styles.avatar}>
                      <img
                        src={
                          (n.self
                            ? user.avatar
                            : selectChatUser.metadata.isGroup
                            ? n.image
                            : selectChatUser.image) || ''
                        }
                        className={styles.img}
                        onError={
                          n.self
                            ? handleAvatarError
                            : selectChatUser.metadata.isGroup
                            ? handleGroupAvatarError
                            : handleAvatarError
                        }
                        alt=""
                      />
                    </div>
                  ) : (
                    ''
                  )}
                </div>
                <div className={styles.chatMain}>
                  <div className={`${styles.mainContent} ${styles[n.type]}`}>
                    {n.quotedMsgId ? (
                      <div className={styles.replyMessage}>
                        {n.quotedMsgBody}
                      </div>
                    ) : null}

                    {n.type === 'chat' ? n.content : ''}
                    {n.type === 'image' ? (
                      <div>
                        <img src={n.content} className={styles.img} />
                        <div>{n.caption}</div>
                      </div>
                    ) : null}
                    {n.type === 'video' ? (
                      <video
                        src={n.content}
                        className={styles.img}
                        controls={true}
                      />
                    ) : null}
                    {n.type === 'ptt' || n.type === 'audio' ? (
                      <audio
                        src={n.content}
                        className={styles.audio}
                        controls={true}
                        controlsList="nodownload"
                      />
                    ) : null}
                    {n.type === 'document' ? (
                      <div className={styles.filecon}>
                        <img src={imgFileIcon} className={styles.img} />
                        <span>{n.caption}</span>
                      </div>
                    ) : null}
                    {n.type === 'chat' ? (
                      <div className={styles.function}>
                        <Dropdown
                          overlay={() => chatFuntionBlock(n)}
                          placement="bottomRight"
                          trigger={['click']}
                        >
                          <DownOutlined />
                        </Dropdown>
                      </div>
                    ) : null}
                  </div>
                  <div className={styles.bar}>
                    <span className={styles.item}>
                      {moment(n.sendDate).format('HH:mm')}
                    </span>
                    {n.isNote === 'Y' ? (
                      <span className={styles.item}>Note</span>
                    ) : (
                      <span className={styles.item}>WhatsApp</span>
                    )}

                    {/* <span className={styles.item}>{n.chatName}</span> */}
                    <span className={styles.item}>{n.senderName}</span>
                  </div>
                  {n.loading ? (
                    <LoadingOutlined className={styles.chatLoading} />
                  ) : (
                    ''
                  )}
                </div>
              </div>
            ))}
          </div>
          {msgtab === '1' && replyMsg.messagesId ? (
            <div className={styles.replyContent}>
              <div className={styles.replyQuote}>
                <div className={styles.rqauthor}>
                  {replyMsg.self === 1
                    ? intl.formatMessage({ id: 'u' })
                    : replyMsg.senderName}
                </div>
                <div className={styles.rqcontent}>{replyMsg.content}</div>
              </div>
              <CloseOutlined
                className={styles.replyColse}
                onClick={onClearReplyMsg}
              />
            </div>
          ) : null}
          <div
            className={`${styles.chatInputbox} ${
              msgtab === '2' ? styles.note : ''
            }`}
          >
            <div className={styles.cibTabs}>
              <Tabs defaultActiveKey="1" onChange={onChangeTab}>
                <TabPane
                  tab={intl.formatMessage({ id: 'reply' })}
                  key="1"
                ></TabPane>
                <TabPane
                  tab={intl.formatMessage({ id: 'note' })}
                  key="2"
                ></TabPane>
              </Tabs>
            </div>
            <div className={styles.sendmsg}>
              <TextArea
                placeholder={intl.formatMessage({ id: 'reply_textarea' })}
                className={styles.sendmsgBox}
                autoSize={true}
                value={chatMessage}
                onChange={onChangeChatMessage}
                onPressEnter={enterSendBtn}
              />
            </div>
            {toBeSentImgs.length > 0 ? (
              <div className={styles.tobesentImgs}>
                {toBeSentImgs.map((n, i) => (
                  <div key={i} className={styles.tbsimg}>
                    <img src={n.url} className={styles.img} alt="" />
                    <CloseOutlined
                      className={styles.icon}
                      onClick={() => onRemoveToBeSentImg(i)}
                    />
                  </div>
                ))}
              </div>
            ) : null}

            <div className={styles.cibFoot}>
              <div className={styles.cibfBars}>
                <span className={styles.barItem}>
                  <Popover
                    content={<Emoji select={onSelectEmoji} />}
                    trigger="click"
                    visible={emojiVisible}
                    onVisibleChange={(visible) => setEmojiVisible(visible)}
                  >
                    <Tooltip title={intl.formatMessage({ id: 'expression' })}>
                      <img
                        src={imgEmoji}
                        alt=""
                        className={styles.barItemIcon}
                      />
                    </Tooltip>
                  </Popover>
                </span>
                <span className={styles.barItem} style={{ paddingTop: 4 }}>
                  <Upload {...uploadProps}>
                    <Tooltip title={intl.formatMessage({ id: 'file' })}>
                      <img
                        src={imgAttach}
                        alt=""
                        className={styles.barItemIcon}
                      />
                    </Tooltip>
                  </Upload>
                </span>

                {msgtab === '1' ? (
                  <span className={styles.barItem}>
                    <Popover
                      content={<QuickReply onSelected={onSelectedQuickReply} />}
                      trigger="click"
                      visible={quickreplyVisible}
                      onVisibleChange={(visible) =>
                        setQuickReplyVisible(visible)
                      }
                    >
                      <Tooltip
                        title={intl.formatMessage({ id: 'quickreplies' })}
                      >
                        <img
                          src={imgQuickReply}
                          alt=""
                          className={styles.barItemIcon}
                        />
                      </Tooltip>
                    </Popover>
                  </span>
                ) : null}
                {msgtab === '1' ? (
                  <span className={styles.barItem} onClick={onClickVoice}>
                    <Tooltip title={intl.formatMessage({ id: 'voice' })}>
                      <img
                        src={imgAudioNote}
                        alt=""
                        className={styles.barItemIcon}
                      />
                    </Tooltip>
                  </span>
                ) : null}
                {voiceStatus ? (
                  <div className={styles.voiceing}>
                    <CloseCircleOutlined
                      className={styles.closeicon}
                      onClick={onCloseVoiceing}
                    />
                    <div className={styles.voicestatus}></div>
                    <div className={styles.voiceingnum}>
                      {moment.utc(voiceDuration * 1000).format('mm:ss')}
                    </div>
                    <CheckCircleOutlined
                      className={styles.checkicon}
                      onClick={onCheckVoiceing}
                    />
                  </div>
                ) : (
                  ''
                )}
              </div>
              <div className={styles.send}>
                <Button
                  type="primary"
                  loading={sendLoading}
                  disabled={sendDisabled}
                  onClick={onSendMessage}
                >
                  {intl.formatMessage({ id: 'send' })}
                </Button>
              </div>
            </div>
          </div>
        </div>
        <div className={`${styles.info} noscrollbar`}>
          <div className={styles.profileDetails}>
            <div className={styles.profileInfo}>
              <div className={styles.profilePic}>
                <div className={styles.avatar}>
                  <img
                    src={chatUserDetail.contact.image}
                    onError={
                      selectChatUser.metadata && selectChatUser.metadata.isGroup
                        ? handleGroupAvatarError
                        : handleAvatarError
                    }
                    className={styles.img}
                    alt=""
                  />
                </div>
                <span className={styles.name}>
                  {chatUserDetail.contact.name}
                </span>
              </div>
              <Button onClick={() => setEditUserVisible(true)}>
                {intl.formatMessage({ id: 'edit' })}
              </Button>
            </div>
            <div className={styles.details}>
              <div className={styles.detail}>
                <span className={styles.name}>
                  {intl.formatMessage({ id: 'firstname' })}
                </span>
                <span className={styles.value}>
                  {chatUserDetail.contact.name}
                </span>
              </div>
              <div className={styles.detail}>
                <span className={styles.name}>
                  {intl.formatMessage({ id: 'lastname' })}
                </span>
                <span className={styles.value}>
                  {chatUserDetail.contact.lastName || '-'}
                </span>
              </div>
              <div className={styles.detail}>
                <span className={styles.name}>
                  {intl.formatMessage({ id: 'email' })}
                </span>
                <span className={styles.value}>
                  <div className="message-content-transformed">
                    {chatUserDetail.contact.email || '-'}
                  </div>
                </span>
              </div>
              <div className={styles.detail}>
                <span className={styles.name}>
                  {intl.formatMessage({ id: 'phonenumber' })}
                </span>
                <span className={styles.value}>
                  <div className="message-content-transformed">
                    {chatUserDetail.contact.phone}
                  </div>
                </span>
              </div>
              <div className={styles.detail}>
                <span className={styles.name}>
                  {intl.formatMessage({ id: 'companyname' })}
                </span>
                <span className={styles.value}>
                  <div className="message-content-transformed">
                    {chatUserDetail.contact.companyName || '-'}
                  </div>
                </span>
              </div>
              <div className={styles.detail}>
                <span className={styles.name}>
                  {intl.formatMessage({ id: 'jobtitle' })}
                </span>
                <span className={styles.value}>
                  <div className="message-content-transformed">
                    {chatUserDetail.contact.jobTitle || '-'}
                  </div>
                </span>
              </div>
              <div className={styles.detail}>
                <span className={styles.name}>
                  {intl.formatMessage({ id: 'contactowner' })}
                </span>
                <span className={styles.value}>
                  <div className="message-content-transformed">
                    {chatUserDetail.contact.assignedName}
                  </div>
                </span>
              </div>
              <div className={styles.detail}>
                <span className={styles.name}>
                  {intl.formatMessage({ id: 'leadstage' })}
                </span>
                <span className={styles.value}>
                  <div className="message-content-transformed">
                    {leadStage.find(
                      (n) => n.value === chatUserDetail.contact.leadStage,
                    )?.label || '-'}
                  </div>
                </span>
              </div>
              <div className={styles.detail}>
                <span className={styles.name}>
                  {intl.formatMessage({ id: 'leadsource' })}
                </span>
                <span className={styles.value}>
                  <div className="message-content-transformed">
                    {leadSource.find(
                      (n) => n.value === chatUserDetail.contact.leadSource,
                    )?.label || '-'}
                  </div>
                </span>
              </div>
              <div className={styles.detail}>
                <span className={styles.name}>
                  {intl.formatMessage({ id: 'priority' })}
                </span>
                <span className={styles.value}>
                  <div className="message-content-transformed">
                    {priority.find(
                      (n) => n.value === chatUserDetail.contact.priority,
                    )?.label || '-'}
                  </div>
                </span>
              </div>
              {/* <div className={styles.detail}>
                <span className={styles.name}>
                  {intl.formatMessage({ id: 'country' })}
                </span>
                <span className={styles.value}>
                  <div className="message-content-transformed">
                    {chatUserDetail.contact.country || '-'}
                  </div>
                </span>
              </div> */}
              <div className={styles.detail}>
                <span className={styles.name}>
                  {intl.formatMessage({ id: 'subscriber' })}
                </span>
                <span className={styles.value}>
                  <div className="message-content-transformed">
                    {intl.formatMessage({
                      id: chatUserDetail.contact.subscriber ? 'yes' : 'no',
                    })}
                  </div>
                </span>
              </div>
              <div className={styles.detail}>
                <span className={styles.name}>
                  {intl.formatMessage({ id: 'lastcontactfromyou' })}
                </span>
                <span className={styles.value}>
                  <div className="message-content-transformed">
                    {chatUserDetail.contact.lastContactFromYou || '-'}
                  </div>
                </span>
              </div>
              <div className={styles.detail}>
                <span className={styles.name}>
                  {intl.formatMessage({ id: 'lastcontactfromcustomers' })}
                </span>
                <span className={styles.value}>
                  <div className="message-content-transformed">
                    {chatUserDetail.contact.lastContactFromCustomers || '-'}
                  </div>
                </span>
              </div>
            </div>
          </div>
          <Labels
            contactId={chatUserDetail.contact.id}
            submited={() => getChatUserList(true)}
          />
        </div>
      </div>

      <EditContact
        visible={editUserVisible}
        onClose={() => setEditUserVisible(false)}
        onSuccess={onUpdateContactSuccess}
        user={chatUserDetail.contact}
      />
    </div>
  );
};

InboxPage.title = 'Inbox';

export default InboxPage;
